package cn.drh.charging.cost.dao.repostitory.impl;


import cn.drh.charging.common.utils.JsonUtils;
import cn.drh.charging.cost.dao.repostitory.CostRuleCacheRepository;
import cn.drh.charging.cost.pojo.po.CostRulePO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @ClassName CostRuleCacheRepositoryImpl
 * @Description TODO
 * @Author renhong~Deng
 * @Date 2025/6/11 15:20
 * @Version 1.0
 */

@Repository
public class CostRuleCacheRepositoryImpl implements CostRuleCacheRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    @Override
    public List<CostRulePO> getCostRuleStationId(Integer stationId) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String costRuleKey = "COST_RULE_KEY_"+stationId;
        Serializable serializable = valueOperations.get(costRuleKey);
        if (serializable != null) {
            List<LinkedHashMap<String,CostRulePO>> list = JsonUtils.fromJson(serializable.toString(), List.class);
            List<CostRulePO> result = new ArrayList<>();
            list.forEach(e->{
                //e   LinkedHashMap<String,CostRulePO>
                //将LinkedHashMap<String,CostRulePO>转化为costRulePO
                CostRulePO costRulePO =  JsonUtils.coverValue(e,CostRulePO.class);
                result.add(costRulePO);
            });
            return result;
        }
        return Collections.emptyList();
    }

    @Override
    public void saveCostRule(Integer stationId,List<CostRulePO> dbCostRules) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String costRuleKey = "COST_RULE_KEY_"+stationId;
        String json = JsonUtils.toJson(dbCostRules);

        valueOperations.set(costRuleKey,json);


    }
}
